<template>
  <div class="directory-browser">
    <el-dialog
      v-model="dialogVisible"
      title="选择目录"
      width="700px"
      :close-on-click-modal="false"
      :before-close="handleClose"
      @closed="onDialogClosed"
    >
      <div class="browser-container">
        <div class="sidebar">
          <el-menu
            default-active="1"
            class="directory-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item
              v-for="(dir, index) in defaultDirectories"
              :key="index"
              :index="dir.path"
            >
              <el-icon><folder /></el-icon>
              <span>{{ dir.name }}</span>
            </el-menu-item>
          </el-menu>
        </div>

        <div class="content">
          <div class="path-bar">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item
                v-for="(part, index) in pathParts"
                :key="index"
                @click="navigateToPart(index)"
              >
                {{ part.name }}
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>

          <div class="file-list">
            <el-table
              :data="directoryContent.directories"
              style="width: 100%"
              @row-dblclick="handleDirectoryDoubleClick"
              height="300"
            >
              <el-table-column width="50">
                <template #default>
                  <el-icon><folder /></el-icon>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="名称" />
              <el-table-column width="80">
                <template #default="scope">
                  <el-button
                    size="small"
                    @click="handleDirectoryDoubleClick(scope.row)"
                  >
                    打开
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <div class="selected-path">
        <span>当前选择: </span>
        <el-input v-model="currentPath" readonly />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import { Folder } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'DirectoryBrowser',
  components: {
    Folder
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    initialPath: {
      type: String,
      default: ''
    }
  },
  emits: ['update:visible', 'select', 'cancel'],
  setup(props, { emit }) {
    const dialogVisible = ref(props.visible)
    const currentPath = ref(props.initialPath || '')
    const defaultDirectories = ref([])
    const directoryContent = reactive({
      directories: [],
      files: []
    })

    // 监听 visible 属性变化
    watch(() => props.visible, (newValue) => {
      console.log('DirectoryBrowser visible changed:', newValue);
      dialogVisible.value = newValue;
      if (dialogVisible.value && !currentPath.value) {
        loadDefaultDirectories();
      }
    });

    // 监听 dialogVisible 变化，同步回 props
    watch(dialogVisible, (newValue) => {
      console.log('DirectoryBrowser dialogVisible changed:', newValue);
      emit('update:visible', newValue);
    });

    // 计算路径部分
    const pathParts = ref([])
    const updatePathParts = () => {
      if (!currentPath.value) {
        pathParts.value = []
        return
      }

      const parts = currentPath.value.split(/[/\\]/)
      const result = []

      // 处理 Windows 路径
      if (currentPath.value.match(/^[A-Z]:\\/i)) {
        result.push({
          name: parts[0],
          path: parts[0] + '\\'
        })
        parts.shift()
      } else if (currentPath.value.startsWith('/')) {
        result.push({
          name: '/',
          path: '/'
        })
      }

      let currentPathBuilder = result.length > 0 ? result[0].path : ''

      for (let i = 0; i < parts.length; i++) {
        if (parts[i]) {
          currentPathBuilder += (currentPathBuilder.endsWith('/') || currentPathBuilder.endsWith('\\') ? '' : '/') + parts[i]
          result.push({
            name: parts[i],
            path: currentPathBuilder
          })
        }
      }

      pathParts.value = result
    }

    // 加载默认目录
    const loadDefaultDirectories = async () => {
      try {
        const response = await fetch('http://localhost:8088/api/reports/default-directories')
        if (!response.ok) {
          throw new Error(`获取默认目录失败: ${response.status}`)
        }

        const data = await response.json()
        if (data.success) {
          defaultDirectories.value = data.data || []

          // 如果有默认目录，选择第一个
          if (defaultDirectories.value.length > 0) {
            currentPath.value = defaultDirectories.value[0].path
            loadDirectoryContent(currentPath.value)
          }
        } else {
          throw new Error(data.message || '获取默认目录失败')
        }
      } catch (error) {
        console.error('加载默认目录失败:', error)
        ElMessage.error('加载默认目录失败: ' + error.message)

        // 使用模拟数据
        defaultDirectories.value = [
          { name: '用户目录', path: 'C:/Users' },
          { name: '桌面', path: 'C:/Users/Desktop' },
          { name: '文档', path: 'C:/Users/Documents' },
          { name: 'C盘', path: 'C:/' },
          { name: 'D盘', path: 'D:/' }
        ]

        currentPath.value = defaultDirectories.value[0].path
        loadDirectoryContent(currentPath.value)
      }
    }

    // 加载目录内容
    const loadDirectoryContent = async (path) => {
      try {
        const response = await fetch(`http://localhost:8088/api/reports/directory-content?path=${encodeURIComponent(path)}`)
        if (!response.ok) {
          throw new Error(`获取目录内容失败: ${response.status}`)
        }

        const data = await response.json()
        if (data.success) {
          directoryContent.directories = data.data.directories || []
          directoryContent.files = data.data.files || []
          currentPath.value = data.data.currentPath
          updatePathParts()
        } else {
          throw new Error(data.message || '获取目录内容失败')
        }
      } catch (error) {
        console.error('加载目录内容失败:', error)
        ElMessage.error('加载目录内容失败: ' + error.message)

        // 使用模拟数据
        directoryContent.directories = [
          { name: 'folder1', path: path + '/folder1' },
          { name: 'folder2', path: path + '/folder2' }
        ]
        updatePathParts()
      }
    }

    // 处理菜单选择
    const handleMenuSelect = (path) => {
      currentPath.value = path
      loadDirectoryContent(path)
    }

    // 处理目录双击
    const handleDirectoryDoubleClick = (directory) => {
      currentPath.value = directory.path
      loadDirectoryContent(directory.path)
    }

    // 导航到路径部分
    const navigateToPart = (index) => {
      if (index < pathParts.value.length) {
        currentPath.value = pathParts.value[index].path
        loadDirectoryContent(currentPath.value)
      }
    }

    // 处理确认
    const handleConfirm = async () => {
      if (!currentPath.value) {
        ElMessage.warning('请选择一个目录')
        return
      }

      try {
        const response = await fetch('http://localhost:8088/api/reports/select-directory', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ path: currentPath.value })
        })

        if (!response.ok) {
          throw new Error(`选择目录失败: ${response.status}`)
        }

        const data = await response.json()
        if (data.success) {
          emit('select', data.data.path)
          dialogVisible.value = false
          emit('update:visible', false)
        } else {
          throw new Error(data.message || '选择目录失败')
        }
      } catch (error) {
        console.error('选择目录失败:', error)

        // 使用模拟数据，直接返回当前路径
        emit('select', currentPath.value)
        dialogVisible.value = false
        emit('update:visible', false)
      }
    }

    // 处理关闭
    const handleClose = () => {
      console.log('DirectoryBrowser: 处理关闭');
      dialogVisible.value = false;
      emit('update:visible', false);
      emit('cancel');
    }

    // 对话框关闭后的回调
    const onDialogClosed = () => {
      console.log('DirectoryBrowser: 对话框已关闭');
      emit('update:visible', false);
    }

    // 初始化
    onMounted(() => {
      console.log('DirectoryBrowser mounted, visible:', props.visible);
      if (props.visible) {
        loadDefaultDirectories();
      }

      // 初始化路径
      if (props.initialPath) {
        currentPath.value = props.initialPath;
        updatePathParts();
      }
    });

    return {
      dialogVisible,
      currentPath,
      defaultDirectories,
      directoryContent,
      pathParts,
      handleMenuSelect,
      handleDirectoryDoubleClick,
      navigateToPart,
      handleConfirm,
      handleClose,
      onDialogClosed
    }
  }
}
</script>

<style scoped>
.directory-browser {
  font-family: Arial, sans-serif;
}

.browser-container {
  display: flex;
  height: 400px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.sidebar {
  width: 200px;
  border-right: 1px solid #dcdfe6;
  overflow-y: auto;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.path-bar {
  padding: 10px;
  border-bottom: 1px solid #dcdfe6;
}

.file-list {
  flex: 1;
  overflow-y: auto;
}

.selected-path {
  margin-top: 15px;
  display: flex;
  align-items: center;
}

.selected-path span {
  margin-right: 10px;
  white-space: nowrap;
}

.directory-menu {
  border-right: none;
}
</style>
